package com.stable.actor.remotedemo;

import com.stable.actor.core.ActorSystem;
import com.stable.actor.core.Props;
import com.stable.actor.network.NetworkClient;
import lombok.extern.slf4j.Slf4j;
/**
 * 远程服务启动器 - 指定具体端口
 */
@Slf4j
public class RemoteServiceStarter {

    public static void main(String[] args) {
        if (args.length < 1) {
            log.info("用法: java RemoteServiceStarter <service-name> [port]");
            log.info("可用服务: payment, inventory, notification");
            return;
        }

        String serviceName = args[0];
        int port = getPortByService(serviceName, args);

        startService(serviceName, port);
    }

    private static int getPortByService(String serviceName, String[] args) {
        // 如果指定了端口，使用指定端口
        if (args.length >= 2) {
            return Integer.parseInt(args[1]);
        }

        // 默认端口映射
        switch (serviceName) {
            case "payment": return 8081;
            case "inventory": return 8082;
            case "notification": return 8083;
            default: return 8080;
        }
    }

    private static void startService(String serviceName, int port) {
        log.info("🌐 启动远程服务: " + serviceName + " 端口: " + port);

        ActorSystem system = new ActorSystem(serviceName + "-System");
        NetworkClient.initialize(system);

        try {
            // 根据服务名创建对应的Actor
            switch (serviceName) {
                case "payment":
                    system.actorOf(Props.create(PaymentServiceActor.class), "payment-service");
                    break;
                case "inventory":
                    system.actorOf(Props.create(InventoryServiceActor.class), "inventory-service");
                    break;
                case "notification":
                    system.actorOf(Props.create(NotificationServiceActor.class), "notification-service");
                    break;
                default:
                    log.info("未知服务: " + serviceName);
                    return;
            }

            log.info("✅ " + serviceName + " 服务已启动在端口: " + port);
            log.info("📍 服务地址: localhost:" + port + "/user/" + serviceName + "-service");

            // 保持运行
            Thread.sleep(300000); // 5分钟

        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } finally {
            system.terminate();
        }
    }
}
